import json
import os
from collections import defaultdict
from datetime import datetime
import configparser
CONFIG_FILE = 'config.ini'
# 转换规则字典
#CONVERSION_RULE = {10: 5, 5: 10, 1: 6, 6: 1, 2: 7, 7: 2, 3: 8, 8: 3, 4: 9, 9: 4}
CONVERSION_RULE = {0:9,1:3,2:5,3:7,4:1,5:9}

def save_settings(total_num,win_cnt):
        config = configparser.ConfigParser()
        config.read(CONFIG_FILE)
        # 创建配置部分
        config['SETTINGS'] = {
            'total_money': config.get('SETTINGS', 'total_money', fallback='5000'),
            'init_money': config.get('SETTINGS', 'init_money', fallback='2'),
            'run_time': config.get('SETTINGS', 'run_time', fallback='24'),
            'ip': config.get('SETTINGS', 'ip', fallback='c145902.sys998.com'),
            'cookie_value': config.get('SETTINGS', 'cookie_value', fallback=''),
            'refresh_time': config.get('SETTINGS', 'refresh_time', fallback='180'),
            'trigger_count': config.get('SETTINGS', 'trigger_count', fallback='1'),
            'profit_money': config.get('SETTINGS', 'profit_money', fallback='5000'),
            'choose_number': config.get('SETTINGS', 'choose_number', fallback='0:9,1:3,2:5,3:7,4:1,5:9'),
            'start_count': config.get('SETTINGS', 'start_count', fallback='20'),
            'total_num': str(total_num),
            'win_cnt': str(win_cnt),
            'right_now': config.get('SETTINGS', 'right_now', fallback='0'),
            'direct': config.get('SETTINGS', 'direct', fallback='<'),
            'jsq': config.get('SETTINGS', 'jsq', fallback='2.5'),
        }
        # 写入配置文件
        with open(CONFIG_FILE, 'w') as configfile:
            config.write(configfile)


def parse_date(time_str):
    """解析时间字符串为日期对象"""
    return datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S").date()


def convert_numbers(numbers):
    """根据规则转换号码列表"""
    return [CONVERSION_RULE.get(n, n) for n in numbers]


def group_data_by_day(items):
    """按open_time字段将数据按天分组"""
    daily_groups = defaultdict(list)
    for item in items:
        date = parse_date(item['open_time'])
        daily_groups[date].append(item)
    return daily_groups


def analyze_daily_data(daily_items):
    """分析单日数据，生成当前期与下期的中奖统计"""
    sorted_items = sorted(daily_items, key=lambda x: x['open_time'])
    results = []

    for i in range(len(sorted_items) - 1):
        current_item = sorted_items[i]
        next_item = sorted_items[i + 1]

        # 解析当前期号码并转换
        current_codes = list(map(int, current_item['open_code'].split(',')))
        converted_codes = convert_numbers(current_codes)
        converted_str = ",".join([f"{n:02d}" for n in converted_codes])

        # 解析下期实际号码
        next_codes = list(map(int, next_item['open_code'].split(',')))
        # 确保有足够的号码进行比较
        if len(next_codes) < 10:
            print(f"警告: 期号 {next_item['issue_no']} 的号码不足10个 ({len(next_codes)}个)")
            next_codes += [0] * (10 - len(next_codes))  # 不足部分补0
        next_codes = next_codes[:10]  # 取前10位
        next_str = ",".join([f"{n:02d}" for n in next_codes])

        # 找出中奖的号码及其位置
        winning_numbers = []
        for pos, (pred, actual) in enumerate(zip(converted_codes, next_codes)):
            if pred == actual:
                winning_numbers.append(f"{pred}({pos + 1})")

        winning_str = ",".join(winning_numbers) if winning_numbers else "无"

        # 正确统计中奖次数（位置匹配数）
        win_count = sum(1 for p, a in zip(converted_codes, next_codes) if p == a)

        results.append({
            "当前期期号": current_item['issue_no'],
            "当前期号码": current_item['open_code'],
            "转换后号码": converted_str,
            "下期期号": next_item['issue_no'],
            "下期实际号码": next_str,
            "中奖次数": win_count,
            "中奖号码": winning_str
        })

    # 计算当日总中奖次数
    total_wins = sum(r["中奖次数"] for r in results) if results else 0
    total_predictions = len(results)

    return {
        "results": results,
        "total_wins": total_wins,
        "total_predictions": total_predictions
    }

def analyze_lottery(data, target_numbers,bet_config):
    results = []
    items = sorted(data, key=lambda x: x['open_time'])
       # 从第二期开始分析（因为第一期没有上一期数据）
    win_count = 0
    for i in range(1, len(items)):
        current_issue = items[i]
        current_open_code = current_issue['open_code']
        current_codes = current_open_code.split(',')

        # 获取上一期数据
        prev_issue = items[i - 1]
        prev_issue_no = prev_issue['issue_no']
        prev_open_code = prev_issue['open_code']
        prev_codes = prev_open_code.split(',')

        # 提取上一期关键号码的位置及对应的号码（位置从1开始）
        # 新增：记录每个位置对应的关键号码（用于匹配下注规则）
        positions_target = [
                {"pos": pos + 1, "code": code} 
                for pos, code in enumerate(prev_codes) 
                if code in target_numbers
            ]

        # 计算当前期的中奖情况
        win_positions = []
        win_codes = []

        # 关键修改：在当前期的相同位置，根据上一期的号码匹配对应下注规则
        for target in positions_target:
            pos = target["pos"]
            prev_code = target["code"]  # 上一期该位置出现的关键号码
            if 0 <= pos - 1 < len(current_codes):
                current_code = current_codes[pos - 1]
                # 按上一期号码对应的规则下注（01位置押01，02位置押02）
                if current_code in bet_config[prev_code]:
                    win_count += 1
                    win_positions.append(pos)
                    win_codes.append(current_code)
    total_predictions = len(results)
    return {
        "results": results,
        "total_wins": win_count,
        "total_predictions": total_predictions
    }


def generate_daily_html_report(date_str, analysis_data, output_dir):
    """生成单日HTML报告"""
    results = analysis_data["results"]
    if not results:
        return None

    # 生成表格行的HTML
    table_rows = ""
    for row in results:
        table_rows += f"""
        <tr>
            <td>{row["当前期期号"]}</td>
            <td>{row["当前期号码"]}</td>
            <td>{row["转换后号码"]}</td>
            <td>{row["下期期号"]}</td>
            <td>{row["下期实际号码"]}</td>
            <td class="win-count">{row["中奖次数"]}</td>
            <td class="winning-numbers">{row["中奖号码"]}</td>
        </tr>
        """

    # 完整HTML内容
    html_content = f"""
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{date_str} 彩票中奖统计报告</title>
    <style>
        body {{ font-family: Arial, sans-serif; max-width: 100%; margin: 0 auto; padding: 15px; }}
        .page-header {{ text-align: center; margin-bottom: 20px; }}
        .stats-card {{ background-color: #f8f9fa; padding: 15px; margin-bottom: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }}
        .stats-title {{ font-size: 18px; font-weight: bold; margin-bottom: 10px; }}
        .stats-grid {{ display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 15px; }}
        .stat-item {{ background-color: white; padding: 12px; border-radius: 5px; border: 1px solid #e0e0e0; }}
        .stat-label {{ font-size: 14px; color: #666; margin-bottom: 5px; }}
        .stat-value {{ font-size: 20px; font-weight: bold; }}
        .section-toggle {{ 
            background-color: #f0f0f0; 
            padding: 12px 15px; 
            border-radius: 5px; 
            cursor: pointer; 
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }}
        .section-toggle:hover {{ background-color: #e8e8e8; }}
        .section-content {{ margin-bottom: 25px; }}
        .toggle-icon {{ transition: transform 0.3s ease; }}
        .collapsed .toggle-icon {{ transform: rotate(180deg); }}
        .collapsed + .section-content {{ display: none; }}
        .table-container {{ overflow-x: auto; -webkit-overflow-scrolling: touch; }}
        .lottery-table {{ width: 100%; min-width: 800px; border-collapse: collapse; }}
        .lottery-table th, .lottery-table td {{ 
            padding: 10px 8px; 
            border: 1px solid #e0e0e0; 
            text-align: center; 
            white-space: nowrap;
            font-size: 14px;
        }}
        .lottery-table th {{ 
            background-color: #f5f5f5; 
            font-weight: bold; 
            position: sticky; 
            top: 0; 
            z-index: 10;
        }}
        .win-count {{ color: #2ecc71; font-weight: bold; }}
        .winning-numbers {{ color: #e67e22; font-weight: bold; }}
        .footer-note {{ text-align: center; color: #666; margin-top: 20px; font-size: 13px; }}
        @media (max-width: 768px) {{
            .lottery-table th, .lottery-table td {{
                padding: 8px 5px;
                font-size: 13px;
            }}
            .stats-grid {{ grid-template-columns: 1fr; }}
        }}
    </style>
    <script>
        // 使用更兼容的DOM加载检测方法
        (function() {{
            // 确保DOM已加载完成
            function init() {{
                var toggles = document.querySelectorAll('.section-toggle');
                for (var i = 0; i < toggles.length; i++) {{
                    toggles[i].addEventListener('click', function() {{
                        this.classList.toggle('collapsed');
                    }});
                }}
            }}

            // 兼容各种浏览器的DOM加载检测
            if (document.readyState === 'complete' || 
                (document.readyState !== 'loading' && !document.documentElement.doScroll)) {{
                init();
            }} else {{
                document.addEventListener('DOMContentLoaded', init);
                window.addEventListener('load', init);
            }}
        }})();
    </script>
</head>
<body>
    <div class="page-header">
        <h1>{date_str} 彩票转换号码中奖统计</h1>
        <p>数据日期：{date_str}</p>
        <p>总记录数：{len(results)}</p>
    </div>

    <!-- 统计汇总模块 -->
    <div class="stats-card">
        <div class="stats-title">每日汇总统计</div>
        <div class="stats-grid">
            <div class="stat-item">
                <div class="stat-label">总预测次数</div>
                <div class="stat-value">{analysis_data["total_predictions"]}</div>
            </div>
            <div class="stat-item">
                <div class="stat-label">总中奖次数</div>
                <div class="stat-value win-count">{analysis_data["total_wins"]}</div>
            </div>
            <div class="stat-item">
                <div class="stat-label">平均每期中奖次数</div>
                <div class="stat-value">{analysis_data["total_wins"] / analysis_data["total_predictions"]:.2f}</div>
            </div>
            <div class="stat-item">
                <div class="stat-label">最高单期中奖次数</div>
                <div class="stat-value">{max(r["中奖次数"] for r in results) if results else 0}</div>
            </div>
        </div>
    </div>

    <!-- 可折叠的详细列表模块 -->
    <div class="section-toggle">
        <div class="toggle-title">点击查看/隐藏详细记录</div>
        <div class="toggle-icon">▼</div>
    </div>
    <div class="section-content">
        <div class="table-container">
            <table class="lottery-table">
                <thead>
                    <tr>
                        <th>当前期期号</th>
                        <th>当前期号码</th>
                        <th>转换后号码</th>
                        <th>下期期号</th>
                        <th>下期实际号码</th>
                        <th class="win-count">中奖次数</th>
                        <th class="winning-numbers">中奖号码(位置)</th>
                    </tr>
                </thead>
                <tbody>
                    {table_rows}
                </tbody>
            </table>
        </div>
    </div>

    <div class="footer-note">
        <p>生成时间：{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}</p>
        <p>数据来源：merged_20250604_200045.json</p>
    </div>
</body>
</html>
    """

    output_filename = os.path.join(output_dir, f"{date_str}_lottery_report.html")
    with open(output_filename, 'w', encoding='utf-8') as f:
        f.write(html_content.strip())
    return output_filename


def analyze_lottery_data(dir_path,file_name,choose_number):
    # 配置路径（请根据实际路径修改）
    global CONVERSION_RULE

    pairs = choose_number.split(',')
    BET_CONFIG = {}
    for pair in pairs:
        key, value = pair.split(':')
        BET_CONFIG[key] = [value]  # 值包装成列表
    TARGET_NUMBERS = list(BET_CONFIG.keys())

    today = datetime.now().strftime("%Y-%m-%d")
    full_path = os.path.join(dir_path, file_name)

    # 读取JSON数据
    try:
        with open(full_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
    except FileNotFoundError:
        print(f"错误：找不到JSON文件 - {full_path}")
        return
    except json.JSONDecodeError:
        print(f"错误：JSON文件格式不正确 - {full_path}")
        return

    # 数据分组与分析
    daily_groups = group_data_by_day(data.get('items', []))

    for date, items in daily_groups.items():
        date_str = date.strftime("%Y-%m-%d")
        if today != date_str:
            continue
        #daily_analysis = analyze_lottery(items,TARGET_NUMBERS,BET_CONFIG)
        daily_analysis = analyze_lottery(items,TARGET_NUMBERS,BET_CONFIG)
        if daily_analysis["total_wins"]:
            total_cnt = len(items)
            total_hits = daily_analysis["total_wins"]
            save_settings(total_cnt,total_hits)
            print(f"{total_cnt}------------->{total_hits}")

if __name__ == "__main__":
    current_date = datetime.now().strftime('%Y%m%d')
    save_dir = f"spider_car_data_{current_date}"
    analyze_lottery_data(save_dir,"merged_20250717_234709.json","01:01,02:02,03:03,04:04")